﻿using System;

namespace suamod.core
{
    using SanlieHash.Fast;
    public class SuaTime
    {
        // expire[0,255] auto +1 [1, 256]
        // 返回时间段 精确到秒 [起始，结尾]
        public static string Now_2025A(byte expire_seconds = 60)
        {
            if (expire_seconds < 0 || expire_seconds > 255) throw new ArgumentException();
            var now = DateTime.UtcNow;
            var end = now.AddSeconds(expire_seconds);
            var _base = new DateTime(end.Year-1, 5, 20, 0, 0, 0, DateTimeKind.Utc);
            var minutes = (int)(now-_base).TotalMinutes;
            var seconds = (byte)( (expire_seconds + now.Second)%0xff);
            if (seconds < expire_seconds) seconds = 0xff;
            byte year_mask = 0;
            if (_base.Year == now.Year) year_mask |= 1;
            else if (_base.Year % 2 != 0) year_mask |= 2;
            return FastEncode.EncodeHex([(byte)(minutes >> 8), (byte)(minutes), (byte)(((minutes >> 13)&0xf8)| year_mask), seconds]);
        }

        public static bool Verify_2025A(string stamp)
        {
            var now = DateTime.UtcNow;
            var _buf = FastEncode.DecodeHex(stamp);
            var minutes = _buf[0] << 8;
            minutes |= _buf[1];
            minutes |= (_buf[2]&0xf8) << 13;
            var year = now.Year;
            if ((_buf[2] & 1) == 0 && year % 2 != ((_buf[2] & 2) >> 1)) year = year - 1;
            var _base = new DateTime(year, 5, 20, 0, 0, 0, DateTimeKind.Utc);
            var start = _base.AddMinutes(minutes);
            var end = start.AddSeconds(_buf[3]);

            return now > start && now < end;
        }
    }
}
